package com.xz.staging.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xz.audit.domain.AuditNode;
import com.xz.common.core.domain.entity.SysDept;
import com.xz.common.utils.StringUtils;
import com.xz.diagnosisOrder.mapper.DiagnosisOrderMapper;
import com.xz.member.mapper.MemberInfoMapper;
import com.xz.member.mapper.WalletRecordMapper;
import com.xz.patient.domain.PatientInfo;
import com.xz.patient.mapper.PatientInfoMapper;
import com.xz.product.domain.ProductCategory;
import com.xz.product.mapper.ProductCategoryMapper;
import com.xz.report.param.SalesReportParam;
import com.xz.report.vo.SalesFlowReportVo;
import com.xz.report.vo.SalesReportVo;
import com.xz.report.vo.SalesReturnReportVo;
import com.xz.sales.mapper.SalesOrderMapper;
import com.xz.sales.mapper.SalesReturnMapper;
import com.xz.staging.service.ISalesStagingService;
import com.xz.staging.vo.FoldLineStagingVo;
import com.xz.staging.vo.FrameLensesRangeVo;
import com.xz.staging.vo.FrameLensesStagingVo;
import com.xz.staging.vo.WorkbenchesVo;
import com.xz.system.service.ISysDeptService;
import com.xz.system.service.impl.SysDeptServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 销售单换货Service业务层处理
 *
 * @author xz
 * @date 2024-2-19 11:15:53
 */
@Service
public class SalesStagingServiceImpl implements ISalesStagingService
{

    @Resource
    private SalesOrderMapper salesOrderMapper;
    @Resource
    private SalesReturnMapper salesReturnMapper;
    @Resource
    private DiagnosisOrderMapper diagnosisOrderMapper;
    @Resource
    private MemberInfoMapper memberInfoMapper;
    @Resource
    private PatientInfoMapper patientInfoMapper;
    @Resource
    private WalletRecordMapper walletRecordMapper;
    @Resource
    private ProductCategoryMapper categoryMapper;
    @Resource
    private ISysDeptService sysDeptService;


    @Override
    public List<WorkbenchesVo> queryData(SalesReportParam salesReportParam) {
        List<WorkbenchesVo> list = new ArrayList<>();
        WorkbenchesVo newWorkbenchesVo = new WorkbenchesVo();
        newWorkbenchesVo.setTodaySum(BigDecimal.ZERO);
        newWorkbenchesVo.setAvgDayMonth(BigDecimal.ZERO);
        newWorkbenchesVo.setCurrMonthSum(BigDecimal.ZERO);
        newWorkbenchesVo.setLastMonthSum(BigDecimal.ZERO);
        // 现在是本月第几天了 今天多少号 就显示多少号之前的日均
        String days = DateUtil.dayOfMonth(new Date())+"";
        BigDecimal dayBigDecimal = new BigDecimal(days);
        WorkbenchesVo salesVo = salesOrderMapper.salesWorkbenches(salesReportParam);
        if(Objects.nonNull(salesVo)){
            salesVo.setBizType(1);
            BigDecimal currMonthSum = salesVo.getCurrMonthSum();
            BigDecimal salesDivide = currMonthSum.divide(dayBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
            salesVo.setAvgDayMonth(salesDivide);
            list.add(salesVo);
        }else{
            newWorkbenchesVo.setBizType(1);
            list.add(newWorkbenchesVo);
        }

//        WorkbenchesVo diagnosisVo = new WorkbenchesVo();
//        diagnosisVo.setBizType(2);
//        BigDecimal diagnosisCurrDay = salesOrderMapper.currDaySum();
//        BigDecimal diagnosisCurrMonth = salesOrderMapper.currMonthSum();
//        BigDecimal diagnosisLastMonth = salesOrderMapper.lastMonthSum();
//        diagnosisVo.setCurrMonthSum(diagnosisCurrMonth);
//        diagnosisVo.setTodaySum(diagnosisCurrDay);
//        diagnosisVo.setLastMonthSum(diagnosisLastMonth);
        WorkbenchesVo diagnosisVo = diagnosisOrderMapper.diagnosisWorkbenches(salesReportParam);
        if(Objects.nonNull(diagnosisVo)){
            diagnosisVo.setBizType(2);
            BigDecimal diagnosisCurrMonthSum = diagnosisVo.getCurrMonthSum();
            BigDecimal diagnosisDivide = diagnosisCurrMonthSum.divide(dayBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
            diagnosisVo.setAvgDayMonth(diagnosisDivide);
            list.add(diagnosisVo);
        }else {
            newWorkbenchesVo.setBizType(2);
            list.add(newWorkbenchesVo);
        }


//        WorkbenchesVo deliverVo = new WorkbenchesVo();
//        deliverVo.setBizType(3);
//        BigDecimal deliverCurrDay = salesOrderMapper.currDaySum();
//        BigDecimal deliverCurrMonth = salesOrderMapper.currMonthSum();
//        BigDecimal deliverLastMonth = salesOrderMapper.lastMonthSum();
//        deliverVo.setCurrMonthSum(deliverCurrMonth);
//        deliverVo.setTodaySum(deliverCurrDay);
//        deliverVo.setLastMonthSum(deliverLastMonth);

            WorkbenchesVo deliverVo = new WorkbenchesVo();
        if(Objects.nonNull(deliverVo))    {
            deliverVo.setBizType(3);
            list.add(deliverVo);
        }else{
            newWorkbenchesVo.setBizType(3);
            list.add(deliverVo);
        }

        WorkbenchesVo rechargeVo = walletRecordMapper.rechargeWorkbenches(salesReportParam);
        if(Objects.nonNull(rechargeVo)){
            rechargeVo.setBizType(4);
            BigDecimal rechargeCurrMonthSum = rechargeVo.getCurrMonthSum();
            BigDecimal rechargeDivide = rechargeCurrMonthSum.divide(dayBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
            rechargeVo.setAvgDayMonth(rechargeDivide);
            list.add(rechargeVo);
        }else{
            newWorkbenchesVo.setBizType(4);
            list.add(deliverVo);
        }


        WorkbenchesVo patientVo = patientInfoMapper.patientWorkbenches(salesReportParam);
        if(Objects.nonNull(patientVo)){
            BigDecimal patientCurrMonthSum = patientVo.getCurrMonthSum();
            BigDecimal patientDivide = patientCurrMonthSum.divide(dayBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
            patientVo.setAvgDayMonth(patientDivide);
            patientVo.setBizType(5);
            list.add(patientVo);
        }else {
            newWorkbenchesVo.setBizType(5);
            list.add(deliverVo);
        }


        WorkbenchesVo memberVo = memberInfoMapper.memberWorkbenches(salesReportParam);
        if(Objects.nonNull(memberVo)){
            BigDecimal memberCurrMonthSum = memberVo.getCurrMonthSum();
            BigDecimal memberDivide = memberCurrMonthSum.divide(dayBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
            memberVo.setAvgDayMonth(memberDivide);
            memberVo.setBizType(6);
            list.add(memberVo);
        }else {
            newWorkbenchesVo.setBizType(6);
            list.add(deliverVo);
        }

        return list;
    }

    @Override
    public List<WorkbenchesVo> hotSalesProduct(SalesReportParam salesReportParam){
        return salesOrderMapper.hotSalesProduct(salesReportParam);
    }

    @Override
    public List<FoldLineStagingVo> foldLineStatistics(SalesReportParam salesReportParam){

        List<FoldLineStagingVo> voList = new ArrayList<>();
        if(salesReportParam.getBizType().equals(1)){
            voList = salesOrderMapper.foldLineStatistics(salesReportParam);
        }else if(salesReportParam.getBizType().equals(2)){
            voList = diagnosisOrderMapper.foldLineStatistics(salesReportParam);
        }else if(salesReportParam.getBizType().equals(3)){
            voList = walletRecordMapper.foldLineStatistics(salesReportParam);
        }

        int currMonth = DateUtil.thisMonth()+1;
        String monthStr = currMonth+"";
        if(currMonth<10){
            monthStr = "0"+currMonth;
        }
        int currYear = DateUtil.thisYear();
        // 本月 或者 近12月数据处理
        if(salesReportParam.getQueryType().equals(2)){
            List<String> dayCollect = voList.stream().map(FoldLineStagingVo::getXValue).collect(Collectors.toList());
            Map<String,FoldLineStagingVo> dayMap = new HashMap<>();
            // 本月
            int currDay = DateUtil.thisDayOfMonth();
            for (int i = 1; i < currDay+1; i++) {
                String dayStr = i+"";
                if(i<10){
                    dayStr = "0"+i;
                }
                String dayKey = currYear + "-" + monthStr + "-" + dayStr;
                if(!dayCollect.contains(dayKey)){
                    FoldLineStagingVo stagingVo = new FoldLineStagingVo();
                    stagingVo.setXValue(dayKey);
                    stagingVo.setYValue(BigDecimal.ZERO);
                    voList.add(stagingVo);
                }
            }
        }else {
            // 近12月
            Map<String,FoldLineStagingVo> monthMap = new HashMap<>();
            List<String> monthCollect = voList.stream().map(FoldLineStagingVo::getXValue).collect(Collectors.toList());
            int i = currMonth - 12;
            if(i<0){
                // 上一年
                int lastYear = currYear - 1;
                // 先把今年1月到当前月塞一下
                for (int j = 1; j <currMonth+1 ; j++) {
                    String monthKey = "";
                    if(j<10){
                        monthKey = currYear+"-0"+j;
                    }else{
                        monthKey = currYear+"-"+j;
                    }
                    if(!monthCollect.contains(monthKey)){
                        FoldLineStagingVo stagingVo = new FoldLineStagingVo();
                        stagingVo.setXValue(monthKey);
                        stagingVo.setYValue(BigDecimal.ZERO);
                        voList.add(stagingVo);
                    }
                }
                // 再加上一年的
                int i1 = 0 - i;
                for (int j = 11-i1; j < 13; j++) {
                    String monthKey = "";
                    if(j<10){
                        monthKey = lastYear+"-0"+j;
                    }else{
                        monthKey = lastYear+"-"+j;
                    }
                    if(!monthCollect.contains(monthKey)){
                        FoldLineStagingVo stagingVo = new FoldLineStagingVo();
                        stagingVo.setXValue(monthKey);
                        stagingVo.setYValue(BigDecimal.ZERO);
                        voList.add(stagingVo);
                    }
                }

            }else {
                for (int j = 1; j < 13; j++) {
                    String monthKey = "";
                    if(j<10){
                        monthKey = currYear+"-0"+j;
                    }else{
                        monthKey = currYear+"-"+j;
                    }
                    if(!monthCollect.contains(monthKey)){
                        FoldLineStagingVo stagingVo = new FoldLineStagingVo();
                        stagingVo.setXValue(monthKey);
                        stagingVo.setYValue(BigDecimal.ZERO);
                        voList.add(stagingVo);
                    }
                }
            }
            System.out.println(monthMap.toString());
        }

        voList = voList.stream().sorted(Comparator.comparing(FoldLineStagingVo::getXValue)).collect(Collectors.toList());
        return voList;
    }

    @Override
    public List<FoldLineStagingVo> foldLineMonthList(SalesReportParam salesReportParam) {
        List<FoldLineStagingVo> voList = new ArrayList<>();
        if (salesReportParam.getBizType().equals(1)) {
            voList = salesOrderMapper.foldLineMonthList(salesReportParam);
        } else if (salesReportParam.getBizType().equals(2)) {
            voList = diagnosisOrderMapper.foldLineMonthList(salesReportParam);
        } else if (salesReportParam.getBizType().equals(3)) {
            voList = walletRecordMapper.foldLineMonthList(salesReportParam);
        }


        // 查完后查部门名称数据
        if (!CollectionUtils.isEmpty(voList)) {
            List<Long> deptIds = voList.stream()
                    .filter(a -> StringUtils.isEmpty(a.getDeptName()) && null != a.getDeptId())
                    .map(FoldLineStagingVo::getDeptId).collect(Collectors.toList());

           if(!CollectionUtils.isEmpty(deptIds)){
               List<SysDept> deptNames = sysDeptService.selectDeptByIds(deptIds);
               voList.forEach(vo -> {
                   if (StringUtils.isEmpty(vo.getDeptName()) && null != vo.getDeptId()) {
                       SysDept dept = deptNames.stream().filter(a -> a.getId().equals(vo.getDeptId())).findFirst().get();
                       vo.setDeptName(null == dept ? null : dept.getDeptName());
                   }
               });
           }

        }
        return voList;
    }

    @Override
    public List<FrameLensesStagingVo> frameLensesList(SalesReportParam salesReportParam){
        List<FrameLensesStagingVo> voList = new ArrayList<>();
        // 查询 框架镜片
        List<String> nameList = new ArrayList<>();
        nameList.add("镜架");
        nameList.add("镜片");
        List<ProductCategory> productCategoryList = categoryMapper.findIds(nameList);
        if(!CollectionUtils.isEmpty(productCategoryList)){
            List<Long> collect = productCategoryList.stream().map(ProductCategory::getId).collect(Collectors.toList());
            salesReportParam.setCategoryIdListStr(StringUtils.join(collect,","));
        }else {
            salesReportParam.setCategoryIdListStr("-1");
        }
        List<FrameLensesStagingVo> frameLensesStagingVos = salesOrderMapper.frameLensesList(salesReportParam);
        Map<String,FrameLensesStagingVo> map = new HashMap<>();
        map.put("1",null);
        map.put("2",null);
        map.put("3",null);
        map.put("4",null);
        map.put("5",null);
        map.put("6",null);
        if(!CollectionUtils.isEmpty(frameLensesStagingVos)){
            for (FrameLensesStagingVo vo:frameLensesStagingVos) {
                if(vo.getOrderSellingPrice().doubleValue()<1000){
                    processData(vo,"1",map);
                }else if(vo.getOrderSellingPrice().doubleValue()>=1000 && vo.getOrderSellingPrice().doubleValue()<2000){
                    processData(vo,"2",map);
                }else if(vo.getOrderSellingPrice().doubleValue()>=2000 && vo.getOrderSellingPrice().doubleValue()<3000){
                    processData(vo,"3",map);
                }else if(vo.getOrderSellingPrice().doubleValue()>=3000 && vo.getOrderSellingPrice().doubleValue()<4000){
                    processData(vo,"4",map);
                }else if(vo.getOrderSellingPrice().doubleValue()>=4000 && vo.getOrderSellingPrice().doubleValue()<5000){
                    processData(vo,"5",map);
                }else if(vo.getOrderSellingPrice().doubleValue()> 5000 ){
                    processData(vo,"6",map);
                }
            }
        }

        for (Map.Entry<String, FrameLensesStagingVo> entry : map.entrySet()) {
            FrameLensesStagingVo value = entry.getValue();
            if(Objects.isNull(value)){
                FrameLensesStagingVo stagingVo = new FrameLensesStagingVo();
                stagingVo.setOrderNum(0);
                stagingVo.setOrderSubtotal(BigDecimal.ZERO);
                voList.add(stagingVo);
            }else {
                voList.add(value);
            }
        }

        return voList;
    }

    @Override
    public List<FrameLensesStagingVo> findFrameLensesList(SalesReportParam salesReportParam){
        List<FrameLensesStagingVo> voList = new ArrayList<>();
        // 查询 框架镜片
        List<String> nameList = new ArrayList<>();
        nameList.add("镜架");
        nameList.add("镜片");
        List<ProductCategory> productCategoryList = categoryMapper.findIds(nameList);
        if(!CollectionUtils.isEmpty(productCategoryList)){
            List<Long> collect = productCategoryList.stream().map(ProductCategory::getId).collect(Collectors.toList());
            salesReportParam.setCategoryIdListStr(StringUtils.join(collect,","));
        }else {
            salesReportParam.setCategoryIdListStr("-1");
        }
        List<FrameLensesStagingVo> frameLensesStagingVos = salesOrderMapper.frameLensesRangeList(salesReportParam);
        if(!CollectionUtils.isEmpty(frameLensesStagingVos)){
            return frameLensesStagingVos;
        }else {
            return voList;
        }

    }

    @Override
    public List<FrameLensesRangeVo> frameLensesRangList(SalesReportParam salesReportParam){
        List<FrameLensesStagingVo> frameLensesList = salesReportParam.getFrameLensesList();
        List<FrameLensesRangeVo> voList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(frameLensesList)){
            List<Long> collect = frameLensesList.stream().map(FrameLensesStagingVo::getSalesId).collect(Collectors.toList());
            salesReportParam.setIdList(collect);
            List<FrameLensesRangeVo> salesDetailList = salesOrderMapper.rangeSalesDetailList(salesReportParam);
            if(!CollectionUtils.isEmpty(salesDetailList)){
                PatientInfo queryPatientInfo = new PatientInfo();
                List<PatientInfo> patientInfoList = patientInfoMapper.selectPatientInfoList(queryPatientInfo);
                Map<Long,String> patientMap = new HashMap<>();
                for (PatientInfo patientInfo:patientInfoList) {
                    patientMap.put(patientInfo.getId(),patientInfo.getPatientName()+"/"+patientInfo.getSexStr()+"/"+patientInfo.getAge()+"岁");
                }
                salesDetailList.stream().forEach(o->{
                    o.setPatientInfo(patientMap.get(o.getPatientId()));
                });
            }
            return salesDetailList;
        }
        return voList;
    }

    private void processData(FrameLensesStagingVo vo,String type,Map<String,FrameLensesStagingVo> map){
        if(Objects.nonNull(map.get(type))){
            FrameLensesStagingVo frameLensesStagingVo = map.get(type);
            Integer orderNum = frameLensesStagingVo.getOrderNum();
            orderNum = orderNum+1;
            frameLensesStagingVo.setOrderNum(orderNum);
            BigDecimal orderSubtotal = frameLensesStagingVo.getOrderSubtotal();
            orderSubtotal = orderSubtotal.add(vo.getOrderSubtotal());
            frameLensesStagingVo.setOrderSubtotal(orderSubtotal);
            map.put(type,frameLensesStagingVo);
        }else {
            FrameLensesStagingVo frameLensesStagingVo = new FrameLensesStagingVo();
            frameLensesStagingVo.setOrderSubtotal(vo.getOrderSubtotal());
            frameLensesStagingVo.setOrderNum(1);
            map.put(type,frameLensesStagingVo);
        }
    }

    @Override
    public boolean saveBatch(Collection entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdateBatch(Collection entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean updateBatchById(Collection entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdate(Object entity) {
        return false;
    }

    @Override
    public Object getOne(Wrapper queryWrapper, boolean throwEx) {
        return null;
    }

    @Override
    public Map<String, Object> getMap(Wrapper queryWrapper) {
        return null;
    }

    @Override
    public BaseMapper getBaseMapper() {
        return null;
    }

    @Override
    public Class getEntityClass() {
        return null;
    }

    @Override
    public Object getObj(Wrapper queryWrapper, Function mapper) {
        return null;
    }
}
